<?php

/**
 * Класс лицензии
 * 
 * @author Gennadiy Kozlenko
 */
class License {
    
    /**
     * Key versions
     * @var string
     */
    const VERSION_1 = 1;
    const VERSION_2 = 2;
    const VERSION_LATEST = self::VERSION_2;
    
    /**
     * CI Istance
     * @var object
     */
    private $obj = null;
    
    /**
     * Last error
     * @var string
     */
    private $lastError = '';
    
    /**
     * Class constructor
     */
    public function __construct() {
        $this->obj =& get_instance();
        $this->obj->load->helper('http');
    }
    
    /**
     * Check activated application
     */
    public function isActivated() {
        $privateKey = $this->obj->variables->get('private_key');
        $version = (int) $this->obj->variables->get('private_key_version', 1);
        $privateKey == $this->generatePrivateKey($version);
        return $privateKey;
    }
    
    /**
     * Activate application
     * @param string $license
     */
    public function activate($license, $email) {
        $url = 'http://hwdteam.ru/license/license.html?code=' . urlencode($license) . '&email=' . urlencode($email) . '&ip=' . urlencode(gethostbyname(php_uname('n'))) . '&dir=' . urlencode(realpath(FCPATH));
        $content = get_content($url);
        
        $match = array();
        $code = '';
        $error = '';
        if (preg_match('~<code>(.*?)</code>~msi', $content, $match)) {
            $code = trim($match[1]);
        }
        if (preg_match('~<error>(.*?)</error>~msi', $content, $match)) {
            $error = trim($match[1]);
        }
        if (!empty($code) && empty($error)) {
            $this->obj->variables->set('license', $license);
            $this->obj->variables->set('private_key', $code);
            $this->obj->variables->set('private_key_version', self::VERSION_LATEST);
            return true;
        } elseif (!empty($error)) {
            $this->lastError = $error;
        }
        return false;
    }
    
    /**
     * Get last error
     */
    public function getLastError() {
        return $this->lastError;
    }
    
    /**
     * Generate private key
     */
    private function generatePrivateKey($version = self::VERSION_LATEST) {
        $a = array('H', 'W', 'D', 'L', 'i', 'c', 'e', 'n', 's', 'e');
        $b = array('r', 'e', 'v', 'r', 'e', 'S');
        $key = '';
        switch ($version) {
            case self::VERSION_1:
                $key = md5(gethostbyname(php_uname('n')) . implode('', array_merge($a, array_reverse($b))));
                break;
            case self::VERSION_2:
                $key = md5(gethostbyname(php_uname('n')) . realpath(FCPATH) . implode('', array_merge($a, array_reverse($b))));
                break;
        }
        return $key;
    }
    
}